<?php

declare(strict_types=1);

namespace AdminBundle\Middleware\Auth;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use Core\Common\Container\AdminPermission;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Router\Dispatched;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

/**
 * AdminAuthMiddleware
 * 验证用户是否有路由请求权限
 * @package App\Middleware
 */
class AdminAuthMiddleware implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @Inject()
     * @var RequestInterface
     */
    private $request;

    /**
     * @Inject()
     * @var AdminPermission
     */
    private $adminPermission;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $accountInfo = auth('adminapi')->user();
        $uid = $accountInfo->id;
        if ($accountInfo->account != 'admin') {
            $uri = $this->request->getAttribute(Dispatched::class)->handler->options['alias'] ?? 'None';
            $userPermissions = $this->adminPermission->getUserAllPermissions($uid);
            $role = $this->adminPermission->getPermissionsRoles($uid);
            $uriPermissions = $this->adminPermission->getPermissionsFromUri($uri);
            if ( count(array_intersect($userPermissions, $uriPermissions)) == 0 ) {
                throw new BusinessException(ErrorCode::ERR_NOT_ACCESS);
            }
        }else {
            $role = ['Admin'];
        }
        $request = \Hyperf\Utils\Context::override(ServerRequestInterface::class,function () use ($request,$role){
            return $request->withAttribute('user_role',$role);
        });
        return $handler->handle($request);
    }
}
